<?php
namespace App\Http\Controllers;

use App\Logic\Code;
use App\Logic\miner\Miner;
use App\Logic\NowApi;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Logic\Sms;
use App\Logic\Upload;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Cache;



class CollectiveController extends Controller
{

    /**
     * @OA\Post(
     *     path="/send",
     *     tags={"公共模块"},
     *     summary="发送验证码",
     *     @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 required={"phone","type","scene"},
     *                 @OA\Property(property="phone", type="string", description="手机号"),
     *                 @OA\Property(property="type", type="string", description="类型 reg fog"),
     *                 @OA\Property(property="scene", type="string", description="场景（字母）"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function send(Request $request){
        /**
         * phone
         * type
         * scene
         */
        $post_data = $request->all();

        $validateRule = [
            'phone'                         => 'required',
            'type'                          => 'required',
            'scene'                          => 'required',
        ];
        $errorMsg = [
            'phone.required'                => '手机号不能为空',
            'type.required'                 => '类型不能为空',
            'scene.required'                 => '场景不能为空',
        ];

        $validator = Validator::make($post_data, $validateRule, $errorMsg);
        if ($validator->fails()){
            $errors = $validator->errors()->all();
            return e_msg(300001,$errors[0]);
        }

        $exists = Db::table('user')->where('phone', $post_data['phone'])->count();
        if($exists){
            if ('reg' === $post_data['type']) {
                return e_msg(300004,'该手机号已注册');
            }
        }else{
            // 忘记密码/登陆  获取验证码
            if ('fg' == $post_data['type']) {
                return e_msg(300011,'该手机号未注册账户');
            }
        }

        /**
         * 发送时存储 验证码  存储该验证码发送时间
         * 60s  判断发送间隔是否在60m之内
         */
        $code_key = $post_data['phone'].'_code_'.$post_data['scene'];
        $time_key = $post_data['phone'].'_time_'.$post_data['scene'];

        if (Cache::has($time_key)) {
            $send_time = Cache::get($time_key);
            if(time()-$send_time<15){
                return e_msg(300012,'每次发送间隔15秒');
            }
        }

//        else{
//            Cache::put($code_key, 123456, 600);
//            Cache::put($time_key, time(), 60);
//            return s_msg('发送成功,现在的验证码是123456');
//        }


        //cache($post_data['phone'] . 'code', 123456,120);
        //return s_msg('发送成功（test,collective),现在的验证码是123456');

        $random = mt_rand(100000, 999999);
        $content = '【指兴云】您的验证码是'.$random.',请注意查收(有效时间10分钟)';
        $res = Sms::smsSend($post_data['phone'], $content);
        if($res['code'] === 200){
            Cache::put($code_key, $random, 600);
            Cache::put($time_key, time(), 60);
        }
        return $res;

    }

    /**
     * @OA\Post(
     *     path="/authCode",
     *     tags={"用户"},
     *     summary="指纹验证码",
     *     @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 required={"code"},
     *                 @OA\Property(property="code", type="string", description="手机验证码"),
     *                 @OA\Property(property="phone", type="string", description="手机号"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function authCode(Request $request){


        if($request->has('code') && $request->input('code')){

            $code = $request->input('code');
            $phone = $request->input('phone');
            $scene = $request->path();
            $key = $phone.'_code_'.$scene;

            return Code::code($key,$code);
        }else{
            return e_msg(123456,'请传入手机验证码');
        }

    }

    public function index(Request $request){
        return 'Lumen';
    }

    /**
     * @OA\Post(
     *     path="/config",
     *     tags={"公共模块"},
     *     summary="矿机配置",
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function sys_config()
    {
            $arr = [
                'config_level' => Cache::get('config_level'),
                'config_products' => Cache::get('config_products'),
                'rate' => NowApi::index(),
            ];
           return s_msg('',$arr);

    }
    /**
     * @OA\Post(
     *     path="/config_sys",
     *     tags={"公共模块"},
     *     summary="系统配置",
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function config_sys()
    {
        $brr = Cache::get('config_sys');
        $crr = Cache::get('configs');
        $arr = [
            0 => $brr,
            1 => $crr,
        ];
        return s_msg('',$arr);

    }


    /**
     *
     * @OA\Post(
     *     path="/miner",
     *     tags={"公共模块"},
     *     summary="矿机详情",
     *     @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 required={"mid"},
     *                 @OA\Property(property="mid", type="string", description="矿机idid"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function miner(Request $request)
    {
        return Miner::get_itemcpuid();
    }


    /**
     *
     * @OA\Post(
     *     path="/productXq",
     *     tags={"公共模块"},
     *     summary="矿机详情",
     *     @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                 required={"product_id"},
     *                 @OA\Property(property="product_id", type="string", description="产品id"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function productXq(Request $request)
    {
        if($request->has('product_id')){
            $products = Cache::get('config_products');
            $products_arr = array_column($products,'id');
            if(in_array($request->input('product_id'),$products_arr)){
                $products_arr_key = array_keys($products_arr,$request->input('product_id'))[0];
                $product = $products[$products_arr_key];
                return s_msg('',$product);
            }else{
                return e_msg(300017,'产品id不存在');
            }
        }else{
            return e_msg(300019,'未传入id');
        }

    }

    /**
     * @OA\Post(
     *     path="/clear",
     *     tags={"公共模块"},
     *     summary="清除缓存",
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function clear(){

       // $a = Cache::flush();
        Cache::forget('config_level');
        Cache::forget('config_price');
        Cache::forget('config_products');
        Cache::forget('config_sys');
        Cache::forget('configs');
        return s_msg('清除成功');
    }

    /**
     * @OA\Post(
     *     path="/pic",
     *     tags={"公共模块"},
     *     summary="主图上传",
     *      @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="bearer+token"
     *     ),
     *    @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                  required={"pic"},
     *                 @OA\Property(property="pic", type="string", description="文件对象"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function pic(Request $request)
    {
        if ($request->hasFile('pic')) {

            if ($request->file('pic')->isValid()) {

                $image = $request->file('pic');
                $path=date('Ymd');
                $rel = Storage::put($path,$image);
                $url = get_http_type().$_SERVER['HTTP_HOST'].'/uploads/orders/'.$rel;
                return s_msg('',$url);
            }else{
                return e_msg('请上传有效文件');
            }

        }else{
            return e_msg('您上传的图片为空');
        }

    }

    /**
     * @OA\Post(
     *     path="/pic_base64",
     *     tags={"公共模块"},
     *     summary="pic上传",
     *      @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         description="bearer+token"
     *     ),
     *    @OA\RequestBody(
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(
     *                  required={"pic"},
     *                 @OA\Property(property="pic", type="string", description="字符串"),
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response="200",
     *         description="正常",
     *     )
     * )
     */
    public function pic_base64(Request $request)
    {

        if ($request->has('pic')) {
            $p = $request->input('pic');
            $pic = Upload::base64($p);
            if($pic['status'] === 'ERROR') {
                return $pic;
            }else{
                $pic = get_http_type().$_SERVER['HTTP_HOST'].'/uploads/orders/'.$pic['data'];
            }
            return s_msg('',$pic);
        }else{
            return e_msg(123456,'请上传图片 pic');
        }

    }

    //国家列表
    public function area(){
        $info = DB::table('area')
            ->where('level',2)
            ->get();
        return s_msg('',$info);
    }


    public function test(){

        Redis::setex('site_name',10,'Lumen的redis');
        $bb = Redis::get('site_name');
        dd($bb);
        return Redis::get('site_name');

    }


}
